//获取系统时间
var getTime=new Date()
// 导入数据库
const DB = wx.cloud.database();
// 声明 打卡数据库
const clockin = DB.collection("Clockin");
// 声明消息数据库
const msgManage = DB.collection("MsgManage");
//显示签到总天数
var getclockInDays  = ''
Page({

  /** 
   * 页面的初始数据
   */
  data: {
    //获取打卡天数
    clockInDays : "",
    //存储获取数据库信息
    renderInfo:[],
    sysW: null,
    lastDay: null,
    firstDay: null,
    year: null,
    hasEmptyGrid: false,
    cur_year: '',
    cur_month: '',
    firstDay: null,
    getDate:null,
    month:null,
    display:"none",
    // 每个周日期渲染
    week:[
      {
        wook: "日"
      },{
        wook: "一"
      }, {
        wook: "二"
      }, {
        wook: "三"
      }, {
        wook: "四"
      }, {
        wook: "五"
      }, {
        wook: "六"
      }, 
    ],
    // 小日历标记
    day:[],
    // 大日历打卡标记
    days:[]
  },
  // 将一个星期的号数填入显示界面
   getProWeekList:function(){
     let that=this
     let date=new Date()
     let dateTime = date.getTime(); // 获取现在的时间
     let dateDay = date.getDay();// 获取现在的
     let oneDayTime = 24 * 60 * 60 * 1000; //一天的时间
     let proWeekList;
     let weekday;
    //  console.log(dateTime)
     for (let i = 0; i < 7; i++) {
      let time = dateTime - (dateDay  - i) * oneDayTime;
      proWeekList = new Date(time).getDate(); //date格式转换为yyyy-mm-dd格式的字符串
      weekday = "day[" + i+"].wook"
      that.setData({
        [weekday]: proWeekList
      })
      //that.data.day[i].wook = new Date(time).getDate();
    }
  },
  // 获取用户点击的日期
  dateSelectAction: function (e) {
    let cur_day = e.currentTarget.dataset.idx;
    this.setData({
      todayIndex: cur_day
    })
    console.log(`点击的日期:${this.data.cur_year}年${this.data.cur_month}月${cur_day + 1}日`);
  },
  // 渲染界面 一个周显示
  setNowDate: function () {
    const date = new Date();
    const cur_year = date.getFullYear();
    const cur_month = date.getMonth() + 1;
    const todayIndex = date.getDate();
    console.log(`日期：${todayIndex}`)
    const weeks_ch = ['日', '一', '二', '三', '四', '五', '六'];
    this.calculateEmptyGrids(cur_year, cur_month);
    this.calculateDays(cur_year, cur_month);
    this.setData({
      cur_year: cur_year,
      cur_month: cur_month,
      weeks_ch,
      todayIndex,
    })
  },

  getThisMonthDays(year, month) {
    return new Date(year, month, 0).getDate();
  },
  getFirstDayOfWeek(year, month) {
    return new Date(Date.UTC(year, month - 1, 1)).getDay();
  },
  calculateEmptyGrids(year, month) {
    const firstDayOfWeek = this.getFirstDayOfWeek(year, month);
    let empytGrids = [];
    if (firstDayOfWeek > 0) {
      for (let i = 0; i < firstDayOfWeek; i++) {
        empytGrids.push(i);
      }
      this.setData({
        hasEmptyGrid: true,
        empytGrids
      });
    } else {
      this.setData({
        hasEmptyGrid: false,
        empytGrids: []
      });
    }
  },
  calculateDays(year, month) {
    let days = [];
    let weekday;
    const thisMonthDays = this.getThisMonthDays(year, month);

    for (let i = 1; i <= thisMonthDays; i++) {
      // days[i].push(i); days[3].item

      weekday = "days[" + (i - 1) + "].item"
      console.log("----------->"+weekday)
      this.setData({
        [weekday]:i,
        src:''
      })
    }

    
    console.log(this.data.days)
  },
  handleCalendar(e) {
    const handle = e.currentTarget.dataset.handle;
    const cur_year = this.data.cur_year;
    const cur_month = this.data.cur_month;
　　
     this.setData({
       days:[]
     })

    if (handle === 'prev') {
      let newMonth = cur_month - 1;
      let newYear = cur_year;
      if (newMonth < 1) {
        newYear = cur_year - 1;
        newMonth = 12;
      }

      this.calculateDays(newYear, newMonth);
      this.calculateEmptyGrids(newYear, newMonth);

      let firstDay = new Date(newYear, newMonth - 1, 1);
      this.data.firstDay = firstDay.getDay();
      this.setData({
        cur_year: newYear,
        cur_month: newMonth,
        marLet: this.data.firstDay
      })
      if (this.data.month == newMonth) {
        this.setData({
          judge: 1
        })
      } else {
        this.setData({
          judge: 0
        })
      }
    } else {
      let newMonth = cur_month + 1;
      let newYear = cur_year;
      if (newMonth > 12) {
        newYear = cur_year + 1;
        newMonth = 1;
      }

      this.calculateDays(newYear, newMonth);
      this.calculateEmptyGrids(newYear, newMonth);
      let firstDay = new Date(newYear, newMonth - 1, 1);
      this.data.firstDay = firstDay.getDay();
      this.setData({
        cur_year: newYear,
        cur_month: newMonth,
        marLet: this.data.firstDay
      })
      if (this.data.month == newMonth){
        this.setData({
          judge:1
        })
      }else{
        this.setData({
          judge: 0
        })
      }
    }
  },
  dataTime: function () {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth();
    var months = date.getMonth() + 1;

    //获取现今年份
    this.data.year = year;

    //获取现今月份
    this.data.month = months;

    //获取今日日期
    this.data.getDate = date.getDate();

    //最后一天是几号
    var d = new Date(year, months, 0);
    this.data.lastDay = d.getDate();

    //第一天星期几
    let firstDay = new Date(year, month, 1);
    this.data.firstDay = firstDay.getDay();
  },
  onshow:function(){
    this.setData({
      display:"block",
    })
  },
  onhide:function(){
    this.setData({
      display: "none",
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    let i = 0;
    let height = 0;
    this.setNowDate();
    this.getProWeekList()

    this.dataTime();
    var res = wx.getSystemInfoSync();
    // 比例调整屏幕宽度适应日历大小
    let num = res.windowHeight / 12

    //调整比例
    for(; i<num;i++){
      console.log("input for")
      
      if((((res.windowHeight / 12) - i) > 47.00 ) && (((res.windowHeight / 12) - i) < 48.00 )) //num就是最适合比例)
      {
        height = i;
        console.log(height)
        break;
        // console.log((res.windowHeight / 12) - i)
        // console.log(i)
        
      }
    }

    this.setData({
      sysW: (res.windowHeight / 12) - height,//更具屏幕宽度变化自动设置宽度 
      marLet: this.data.firstDay,
      getDate: this.data.getDate,
      judge:1,
      month: this.data.month,
    });

    /**
     * 获取系统信息
     */
    console.log(that.data.month)

    //数据库预加载
    clockin.get({
      success:res => {
        // 加载结束就隐藏
        // console.log(res)
        wx.hideLoading()
        
        this.data.renderInfo = res.data
      }
    })
    //刷新页面 延迟刷新 保证数据能够正确获取 理论数据越大 延时越大
    setTimeout(function(){that.refreshIcon()},1000) 

  },
  //滑动切换
  swiperTab: function (e) {
    var that = this;
    that.setData({
      currentTab: e.detail.current
    });
  },
  //点击切换
  clickTab: function (e) {
    var that = this;
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current,

      })
    }
    // console.log(that.data.nubmerLength)
  },
  upper: function (e) {
    console.log(e)
  },
  lower: function (e) {
    console.log(e)
  },
  scroll: function (e) {
    console.log(e)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.refreshIcon()
    wx.stopPullDownRefresh()

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 打卡
  clockIn:function(){
    let _this = this
    //获取年份
    let year = getTime.getFullYear()
    //获取当前月份 0 - 11 0一月
    let month = getTime.getMonth()
    // 0表示一月 加一才能理解为正常显示
    month += 1
    let dayNum = getTime.getDate()
    //获取当前星期几 0-6 0:星期天
    let nowDay = getTime.getDay() 
    let showTime = month+"月" + dayNum + "号" + getTime.getHours()+":" + getTime.getMinutes()
    // Object.keys(day[nowDay]).length
    //设置小日历打卡图标
    let signInImg = {src:"https://7864-xdaisqliot-1g4ucqpdcb12b67a-1304264748.tcb.qcloud.la/lossPlanIcon/icon/%E7%AD%BE%E5%88%B0.png?sign=671c67cdb060a9ad72411ae24232462d&t=1646125180",wook: dayNum}
    let {day} = this.data
    
    //设置日历打卡图标
    let signInImgs = {src:"https://7864-xdaisqliot-1g4ucqpdcb12b67a-1304264748.tcb.qcloud.la/lossPlanIcon/icon/%E7%AD%BE%E5%88%B0.png?sign=671c67cdb060a9ad72411ae24232462d&t=1646125180", item:dayNum}
    let {days} = this.data 
    // 判断今日是否打卡
    // 小技巧 获取键值对长度 可用于判断数据库是否存在同一个数据 功能在于不能重复打卡
    if(Object.keys(day[nowDay]).length < 2 && Object.keys(days[dayNum-1]).length < 2)
    {
      day[nowDay] = signInImg
      //渲染小日历打卡图标
      _this.setData({
        day
      })

      days[dayNum-1] = signInImgs
      //渲染日历打卡图标
      _this.setData({
        days
      })
      //消息提示框提示
      wx.showToast({
        title: '打卡成功'
      })
      //数据库操作
      clockin.add({
        data:{
          //当前号数
          dnum : dayNum,
          //星期几
          dnow : nowDay,
        }
      })
      // 消息数据库添加打卡消息
      msgManage.add({
        data:{
          type : "打卡通知",
          clockin : "今日已打卡",
          img:"https://7864-xdaisqliot-1g4ucqpdcb12b67a-1304264748.tcb.qcloud.la/lossPlanIcon/icon/%E6%89%93%E5%8D%A1.png?sign=0ae576052d12288887098f72f171c962&t=1646292658",
          date:showTime
        }
      })
    }
    // 如果存在同一条数据 显示已打卡
    else
    {
      console.log("今日已打卡")
      wx.showToast({
        title: '今日已打卡',
        icon:"none"
      })
    }
    
  } ,
  // 日历打卡图标渲染
  refreshIcon:function(){
    let _this = this
    wx.showLoading({
      title: '加载中',
    })
    // 获取打卡数据库全部数据 get
    clockin.get({
      success:res => {
        // 加载结束就隐藏
        // console.log(res)
        wx.hideLoading()
        // 数据转存 用于以下计算天数
        this.data.renderInfo = res.data
      }
    })
    // 计算数据库多少条数据 计算签到天数
    getclockInDays  = Object.keys(this.data.renderInfo).length
    // 将获得的数据绑定 wxml界面显示
    _this.setData({
      clockInDays : getclockInDays 
    })

    // 将数据渲染到界面 数据存在多条 通过遍历的方式进行渲染
    for(let i = 0 ; i < Object.keys(this.data.renderInfo).length; i ++)
    {
      let signInImg = {src:"https://7864-xdaisqliot-1g4ucqpdcb12b67a-1304264748.tcb.qcloud.la/lossPlanIcon/icon/%E7%AD%BE%E5%88%B0.png?sign=671c67cdb060a9ad72411ae24232462d&t=1646125180",wook: this.data.renderInfo[i]["dnum"]}
      let {day} = this.data
      //设置日历打卡图标
      let signInImgs = {src:"https://7864-xdaisqliot-1g4ucqpdcb12b67a-1304264748.tcb.qcloud.la/lossPlanIcon/icon/%E7%AD%BE%E5%88%B0.png?sign=671c67cdb060a9ad72411ae24232462d&t=1646125180", item:this.data.renderInfo[i]["dnum"]}
      let {days} = this.data 

      days[this.data.renderInfo[i]["dnum"]-1] = signInImgs
      // 渲染小日历打卡图标
      _this.setData({
        day
      })
      // 渲染日历打卡图标
      _this.setData({
        days
      })
    }
  }
    
})